package classes;

import finanz.kontrolle.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAdapterGenerico extends BaseAdapter {

	private Activity ctx;
	private Class<?> classeAlvo;
	private ArrayGenerico[] lista;
	private String CampoID;
	private String novo;
	
	public ListAdapterGenerico( Activity ctx, Class<?> classe, ArrayGenerico[] lista, String campoid, String novo ) {
		this.ctx = (Activity) ctx;
		this.classeAlvo = classe;
		this.lista = lista;
		this.CampoID = campoid;
		this.novo = novo;
	}
	
	public int getCount() {
		return this.lista.length + 1;
	}

	public Object getItem(int i) {
		if ( i < 0 )
			return null;

			return this.lista[ i - 1 ];
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	public View getView(int position, View arg1, ViewGroup arg2) {
		LayoutInflater layout = ( LayoutInflater ) ctx.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
		
		View v = layout.inflate( R.layout.lista, null );

		TextView txtId = ( TextView ) v.findViewById( R.id.lstId );
		TextView txtNome = ( TextView ) v.findViewById( R.id.lstNome );

		if ( position == 0 ) {
			txtId.setText( "0" );
			txtNome.setText( this.novo );
		} else {
			txtId.setText( this.lista[ position - 1 ].getID() );
			txtNome.setText( this.lista[ position - 1 ].getLabel() );
		}
		
		v.setOnClickListener( new View.OnClickListener() {
			public void onClick( View v ) {
				
				TextView tvID = ( TextView ) v.findViewById( R.id.lstId );
				
				String id = tvID.getText().toString();
				
				Intent i = new Intent( ctx, classeAlvo );
				i.putExtra( CampoID, id );
				ctx.startActivity( i );
			}
		}  );
		
		return v;
	}
}
